package com.jack.leetcode.每日一题;

public class k个一组翻转链表 {

    public class ListNode {
        int val;
        ListNode next;

        ListNode(int x) {
            val = x;
        }
    }

    public ListNode reverseKGroup(ListNode head, int k) {
        if (head == null || k == 1) {
            return head;
        }
        ListNode begin = new ListNode(0);
        begin.next = head;
        ListNode start = begin;
        ListNode end = begin;
        while (end != null) {
            for (int i = 0; i < k && end != null; i++) {
                end = end.next;
            }
            if (end == null) {
                break;
            }
            ListNode cur = start.next;
            ListNode next = end.next;
            end.next = null;
            start.next = reverse(cur);
            cur.next = next;
            start = cur;
            end = start;
        }
        return begin.next;
    }

    private ListNode reverse(ListNode start) {
        ListNode preNode = null;
        ListNode curNdoe = start;
        ListNode nextNode = null;
        while (curNdoe != null) {
            nextNode = curNdoe.next;
            curNdoe.next = preNode;
            preNode = curNdoe;
            curNdoe = nextNode;
        }
        return preNode;
    }
}
